package com.blog.blogservice.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.blog.blogservice.app.service.CategoryService;
import com.blog.blogservice.domain.entity.Category;
import com.blog.blogservice.infra.mapper.CategoryMapper;
import com.blog.blogservice.util.constant.BlogConstant;
import org.apache.ibatis.executor.BatchResult;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 类别表(Category)应用服务
 *
 * @author guanglin.ma
 * @since 2024-03-02 23:25:31
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询数据
     *
     * @param categorys 查询条件
     * @return 返回值
     */
    @Override
    public List<Category> selectList(Category categorys) {
        return this.list();
    }

    /**
     * 保存数据
     *
     * @param categorys 数据
     */
    @Override
    public List<Category> saveData(List<Category> categorys) {
        categorys.forEach(label -> label.setCategoryCode(BlogConstant.CATEGORY_CODE_PREFIX + System.currentTimeMillis()));
        List<BatchResult> batchResultList = this.categoryMapper.insertBathch(getSqlSessionFactory(), categorys, CategoryMapper.class);
        List<Category> categoryList = batchResultList.get(0).getParameterObjects().stream().map(o -> (Category) o).collect(Collectors.toList());
        //此处虽然是有循环，但是实际数据只有一个，所以不考虑redis网络延迟
        HashMap hashMap = new HashMap<>();
        categoryList.forEach(category -> {
            hashMap.put(category.getCategoryCode(), category.getCategoryName());
        });
        redisTemplate.opsForHash().putAll(BlogConstant.CATEGORY_LIST, hashMap);

        return categoryList;
    }

    /**
     * 删除数据
     *
     * @param categorys
     */
    @Override
    public void deleteData(List<Category> categorys) {
        if (!CollectionUtils.isEmpty(categorys)) {
            categorys.forEach(category -> this.removeById(category.getCategoryId()));
        }
    }

    /**
     * 查询列表
     *
     * @param queryWrapper 实体对象封装操作类 {@link QueryWrapper}
     */
    @Override
    public List<Category> listQueryWrapper(Wrapper<Category> queryWrapper) {
        return super.list(queryWrapper);
    }
}

